<template>
  <div>
    <a-card title="使用电商模板批量制单" :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form>
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="数据源模板上传">
                <div class="table-operator">
                  <a-upload
                    name="file"
                    :multiple="false"
                    :data="data_ec_waybill"
                    :showUploadList="true"
                    :remove="remove"
                    :file-list="fileList_ec_waybill"
                    :beforeUpload="beforeUpload"
                  >
                    <a-button>
                      <UploadOutlined />
                      选择文件
                    </a-button>
                  </a-upload>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="样式模板">
                <a-select
                  allowClear
                  showSearch
                  optionFilterProp="children"
                  placeholder="样式模板"
                  v-model:value="param_ec_waybil.styleTpl"
                  :options="styleTpls"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2" :offset="1">
              <a-form-item>
                <a-button type="primary" @click="generate" :loading="loading"><FileAddOutlined/>生成</a-button>
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <a-form-item>
                <a-button type="primary" @click="clear">重置</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getAction, postDownFile } from "@/utils/request.js"
import moment from "moment";
import { message } from 'ant-design-vue';


// 定义响应式数据
const loading = ref(false);
const param_ec_waybil = ref({
  bizPath: "EC-waybill/templates",
  styleTpl: ''
});
const data_ec_waybill = ref({
  fileName: ""
});
const fileList_ec_waybill = ref([]);
const styleTpls = ref([]);
const bucketName = ref("waybill");
const url = ref({
  oss: "/oss/",
  oss_list: "/oss/list",
  ec_waybill_excel: "/yg/excel_one2many"
});

// 定义计算属性
const downFileName = computed(() => {
  const timestamp = moment(new Date()).format("YYYYMMDDHHmmss");
  return `${data_ec_waybill.value.fileName.split('.')[0]}-${timestamp}.zip`;
});

// 定义方法
const getTpls = async () => {
  try {
    const res = await getAction(url.value.oss, {
      bucketName: bucketName.value,
      bizPath: param_ec_waybil.value.bizPath
    });
    if (res && res.success && Array.isArray(res.data)) {
      styleTpls.value = [];
      res.data.forEach((value, index) => {
        //console.error(value.filePath, index);
        const label = value.filePath.split("/").pop();
        styleTpls.value.push({ id: index, key: index, label, value: value.filePath });
      });
    }
  } catch (error) {
    console.error('获取模板列表失败', error);
  }
};

const remove = () => {
  fileList_ec_waybill.value = [];
};

const clear = () => {
  fileList_ec_waybill.value = [];
  param_ec_waybil.value.styleTpl = '';
  getTpls();
};

const generate = async () => {
  if (!param_ec_waybil.value.styleTpl) {
    message.error('请先选择样式模板！');
    return false;
  }
  if (fileList_ec_waybill.value.length === 0) {
    message.error('请先选择数据模板！');
    return false;
  }
  console.log(`downFileName: ${downFileName.value}`);
  const formData = new FormData();
  fileList_ec_waybill.value.forEach((file) => {
    formData.append('file', file);
  });
  for (const key in param_ec_waybil.value) {
    formData.append(key, param_ec_waybil.value[key]);
  }
  loading.value = true;
  try {
    const data = await postDownFile(url.value.ec_waybill_excel, formData);
    if (!data) {
      message.warning('文件下载失败');
      return;
    }
    const result = await data.text();
    if (result.includes("message") && result.includes("success")) {
      let msg = '';
      try {
        const res = JSON.parse(result);
        msg = res.message;
      } catch (e) {
        console.error(e);
        msg = result;
      }
      message.error(msg, 10);
      return;
    }
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
      window.navigator.msSaveBlob(new Blob([data]), downFileName.value);
    } else {
      const blobUrl = window.URL.createObjectURL(new Blob([data]));
      const link = document.createElement('a');
      link.style.display = 'none';
      link.href = blobUrl;
      link.setAttribute('download', downFileName.value);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(blobUrl);
      fileList_ec_waybill.value.pop();
    }
  } catch (error) {
    console.error('生成文件失败', error);
  } finally {
    loading.value = false;
  }
};

const beforeUpload = (file) => {
  //console.error(file);
  const fileType = file.type;
  if (!fileType.includes('excel') && !fileType.includes('sheet')) {
    message.error('请上传Excel表格文件');
    return false;
  }
  console.log(file.name);
  data_ec_waybill.value.fileName = file.name;
  fileList_ec_waybill.value = [file];
  return false;
};

// 生命周期钩子
onMounted(() => {
  getTpls();
});
</script>

<style lang="less" scoped>
.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px
}

.ant-btn-danger {
  background-color: #ffffff
}

.ant-modal-cust-warp {
  height: 100%
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden
}
</style>